<?php
require_once 'functions.php';

// 获取访问者IP
function get_visitor_ip() {
    $ip = '';
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

// 记录访问
function record_page_visit($page_id) {
    $db = db_connect();
    
    $visitor_ip = get_visitor_ip();
    $current_date = date('Y-m-d');
    $current_time = date('Y-m-d H:i:s');
    $user_agent = $_SERVER['HTTP_USER_AGENT'];

    // 检查今天是否已经记录过这个IP的访问
    $check_sql = "SELECT id FROM page_visits 
                 WHERE page_id = :page_id 
                 AND visitor_ip = :visitor_ip 
                 AND visit_date = :visit_date";
    
    $stmt = $db->prepare($check_sql);
    $stmt->execute([
        ':page_id' => $page_id,
        ':visitor_ip' => $visitor_ip,
        ':visit_date' => $current_date
    ]);
    
    // 如果今天没有记录过这个IP的访问，则添加记录
    if ($stmt->rowCount() === 0) {
        $insert_sql = "INSERT INTO page_visits 
                      (page_id, visitor_ip, visit_date, visit_time, user_agent) 
                      VALUES (:page_id, :visitor_ip, :visit_date, :visit_time, :user_agent)";
        
        $stmt = $db->prepare($insert_sql);
        $stmt->execute([
            ':page_id' => $page_id,
            ':visitor_ip' => $visitor_ip,
            ':visit_date' => $current_date,
            ':visit_time' => $current_time,
            ':user_agent' => $user_agent
        ]);
    }
}

// 如果是AJAX请求，记录访问
if (isset($_POST['page_id'])) {
    $page_id = $_POST['page_id'];
    record_page_visit($page_id);
    echo json_encode(['success' => true]);
}
